package test.com.aop;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * Created on 2016/12/26.
 */
@Component
@Aspect
public class Aspect1 {

    Logger logger = Logger.getLogger(getClass());

    @Around("execution (* test.com.service..*.*(..)) && !execution(* test.com.service.Service1.m2(..)) ")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        String paramsString = null;
        String fullMethodName = null;
        try {
            Signature signature = point.getSignature();
            String fullInterface = signature.getDeclaringTypeName();
            String methodName = signature.getName();
            fullMethodName = fullInterface + "." + methodName + "()";
            Object[] params = point.getArgs();
            try {
                paramsString = JSON.toJSONStringWithDateFormat(params, "yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                logger.error("参数序列化成JSON出错:", e);
            }

        } catch (Exception e) {
            logger.error("异常信息:", e);
        }

        Object object = point.proceed();

        try {
            if (logger.isInfoEnabled()) {

                String msg = "\n============================log begin============================\n" +
                        "method	:" + fullMethodName + "\n" +
                        "params	:" + paramsString + "\n" +
                        "results	:" + JSON.toJSONString(object) + "\n" +
                        "============================log end==============================";

                logger.info(msg);
            }
        } catch (Exception e) {
            logger.error("print log error", e);
        }

        return object;
    }

}
